#!/bin/sh

disk=$1
STATS=`grep $disk /proc/diskstats|awk 'NR==1{print $0}'`

LOCKFILE=/tmp/spinDown.lock
STATFILE=/tmp/spinDown
DOWNFILE=/tmp/spinDown
LOGFILE=/tmp/spinDown.log

if [ -f $LOCKFILE ]; then
    # we are already running
    exit 1
fi
if [ ! -f /sbin/hdparm ];then
   apt-get -f install hdparm
fi
if [ ! -f $LOGFILE ];then
    touch $LOGFILE
fi
touch $LOCKFILE

DATE=`date`

if [ -f ${STATFILE}.${disk}.stat ]; then
    PREVSTATS=`cat ${STATFILE}.${disk}.stat`
    if [ "$STATS" = "$PREVSTATS" ] && [ ! -f ${DOWNFILE}.${disk}.down ]; then
        # Disk stats unchanged and the disk spinning.  Hence, idle -> spin down.
        echo "$DATE ${disk} idle, spinning down" >> /tmp/spinDown.log
        #service smartd stop > /dev/null
        #sdparm --command=sync /dev/${disk} &> /dev/null
        #sdparm --command=stop /dev/${disk} &> /dev/null
	/sbin/hdparm -y /dev/${disk} &> /dev/null
	STATS=`grep $disk /proc/diskstats|awk 'NR==1{print $0}'`
        echo "$STATS" > ${STATFILE}.${disk}.stat
        touch ${DOWNFILE}.${disk}.down
    else
        if [ "$STATS" != "$PREVSTATS" ] && [ -f ${DOWNFILE}.${disk}.down ]; then
            # Disk stats are different & disk was down.  Remove the down state file.
            echo "$DATE stats different for ${disk}" >> /tmp/spinDown.log
            #service smartd start > /dev/null
            rm -f ${DOWNFILE}.${disk}.down
        fi
        if [ "$STATS" != "$PREVSTATS" ]; then
            echo "$STATS" > ${STATFILE}.${disk}.stat
        fi
    fi
else
    # Initialise the state file
    echo "$DATE initialising for ${disk}" >> /tmp/spinDown.log
    echo "$STATS" > ${STATFILE}.${disk}.stat
fi

rm -f $LOCKFILE
if [ `cat /tmp/spinDown.log|wc -l` -gt 200 ];then
	mv /tmp/spinDown.log /tmp/spinDown.log.1
    touch /tmp/spinDown.log
fi
